package com.lwj.springboot.config;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

/**
 * @author LwJ
 * Created by LiWeijie on 2019/7/9.
 */
@Aspect
@Component
public class DynamicDataSourceAop {

    private static Logger log = LogManager.getLogger(DynamicDataSourceAop.class);

    @Pointcut("execution(* com.lwj.springboot.controller.*.*(..))")
    public void pointCut() {

    }

    /**
     * 执行方法前更换数据源
     *
     * @param joinPoint
     */
    @Before("pointCut()")
    public void doBefore(JoinPoint joinPoint) {
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes())
                .getRequest();

        String area = (String) request.getHeader("area");

        log.info("area:" + area);

        if (AreaKeyId.SHENZHEN.getArea().equals(area)) {

            DynamicDataSourceContextHolder.set(AreaKeyId.SHENZHEN);

        } else if (AreaKeyId.HUIZHOU.getArea().equals(area)) {

            DynamicDataSourceContextHolder.set(AreaKeyId.HUIZHOU);
        }
    }

    /**
     * 执行方法后清除数据源设置
     *
     * @param joinPoint
     */
    @After("pointCut()")
    public void doAfter(JoinPoint joinPoint) {
        //清除数据源
        DynamicDataSourceContextHolder.clear();
    }

}
